#include "parser.h"
#include "y.tab.h"

static PARSER * yy_std;
static PARSER * yy_lexical;

/* devolve o parser actual e se for ! NULL fixa esse */
PARSER * switchParser(PARSER * new)
{
	PARSER * temp = yy_lexical;
	
	if(!new){return yy_lexical;}
	
	yy_lexical = new;
	
	return temp;
}

void initLexical (char * file)
{
	yy_std = NewParser("<<stdin>>");
	
	/* por default stdin (what else...) */
	if(file == NULL)
	{
		yy_lexical = yy_std;
	}else{
		yy_lexical = NewParser(file);
	}
}

void deleteLexical(void)
{
	DeleteParser(yy_lexical);
	if (yy_lexical != yy_std) DeleteParser(yy_std);
}

void restartLexical (void)
{
	deleteLexical();
	yy_lexical = NewParser( "<<stdin>>" );
	yy_std = yy_lexical;
}


PARSER * newFile(char * a) 
{
	return NewParser(a);
}

PARSER * switchStdin(void)
{
	return	switchParser(yy_std);
}

void destroyLexical(PARSER * parser)
{
	DeleteParser(parser);
}

/* TODO: avisar os gajos da gnu que o flex não vale nada */
int yylex(void)
{
	int n = parser(yy_lexical);
#ifdef DEBUG_LEXICAL_OUTPUT
	if(n<257)
		printf("lex'ed : %c\n", n);
	else
		printf("lex'ed : %s\n", yy_lexical->buffer);
#endif
	switch(n)
	{
		case INTEIRO:
			yylval.i = atoi(yy_lexical->buffer);
			break;
		case TOKEN: case STRING:
			yylval.s = yy_lexical->buffer;
			break;
		case CHAR:
			yylval.i = yy_lexical->buffer[0];
			break;
		case REAL:
			yylval.d = atof(yy_lexical->buffer);
			break;
		default:
			break;
	}
	return n;
			
}

int currentLine(void)
{
	return FetchLine(yy_lexical);
}

int currentNumber(void)
{
	return FetchNumber(yy_lexical);
}
